package com.easy.generator.vue;

import com.easy.generator.Easy;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.time.LocalDate;
import java.util.Set;

/**
 * @author easy
 * @date 2025年07月11日 16:19
 */
public class Router_Generator {
    private static final String DIR_NAME = Easy.VUE_LOCAL_PATH;
    private static final String FILE_NAME = "index.js";
    private static final String DEST_PATH = Easy.VUE_LOCAL_PATH + "/src/router";


    public static void generate() throws Exception {
        StringBuilder strb = new StringBuilder();
        strb.append("// 1. 要有组件\n");
        strb.append("import { createWebHashHistory, createRouter } from 'vue-router';\n");
        strb.append("// 2. 定义一些路由（路径与组件之间的映射）\n");
        strb.append("const routes = [\n");
        strb.append("    // 后台管理员\n");
        strb.append("    {name: 'login',path: '/login', component: ()=>import('@/view/Login.vue')},\n");
        strb.append("    {name: 'index', path: '/', component: ()=>import('@/view/Index.vue'), children: [\n");
        // 获取类加载器
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        // 扫描包下的所有类
        Set<Class<?>> classes = Easy.scanClasses(Easy.BEAN_PACKAGE, classLoader);
        // 为每个实体类生成Controller
        for (Class<?> clazz : classes) {
            if (Easy.isEntityClass(clazz)) {
                strb.append("            {name: '"+clazz.getSimpleName().toLowerCase()+"',path: '/"+clazz.getSimpleName().toLowerCase()+"', component: ()=>import('@/view/"+clazz.getSimpleName()+".vue')},\n");
            }
        }
        strb.append("        ]},\n");
        strb.append("];\n");
        strb.append("// 3. 创建路由\n");
        strb.append("const router = createRouter({\n");
        strb.append("    history: createWebHashHistory(),    // 历史记录\n");
        strb.append("    routes: routes,\n");
        strb.append("});\n");
        strb.append("// 路由是否已经加载\n");
        strb.append("router.load = false;\n");
        strb.append("// 4. 暴露\n");
        strb.append("export default router\n");
        String content = String.format(strb.toString(), LocalDate.now());
        File outputFile = new File(DEST_PATH + "/" + FILE_NAME);
        if (!outputFile.exists()) {
            outputFile.getParentFile().mkdirs();
            outputFile.createNewFile();
        }
        try (FileWriter writer = new FileWriter(outputFile)) {
            writer.write(content);
        }
        System.out.println("已生成文件：" + outputFile.getAbsolutePath());
    }

}
